package com.qf.day30_springbootstarter.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/*
 * 文本文件追加器
 * */
public class FileAppender {

    /*文本文件的绝对路径*/
    private String filepath;

    private BufferedWriter bufferedWriter;

    public FileAppender(String filepath) throws IOException {
        this.filepath = filepath;

        // 初始化 bufferedWriter，目的是让每个fileAppender对象只有一个bufferedWriter对象，避免重复创建
        this.bufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
    }

    /*把data追加到文本文件中
     * data List<String>*/
    public Integer appendListToFile(List<String> data) throws IOException {

        int count = 0;
        for (String line : data) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            count++;
        }
        return count;
    }

    /*关闭资源*/
    public void close() throws IOException {
        bufferedWriter.close();
    }

}
